package com.smm.web.vmc.controller.User;

import com.smm.web.vmc.dao.BaseDao;
import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.dto.JsonReturn;
import com.smm.web.vmc.service.UserService;
import com.smm.web.vmc.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhenghao on 2016/9/5.
 * 用户修改密码
 */
@Slf4j
@Controller
@RequestMapping("/home")
public class UpdatePasswrodController {

    @Resource
    private BaseDao<User> userBaseDao;


    @RequestMapping("/alertPw.do")
    public ModelAndView alertPw(){
        return new ModelAndView("alertPw");
    }


    @RequestMapping("/submitAlertPwd.do")
    @ResponseBody
    public JsonReturn submitAlertPwd(String password,String newPassword,HttpServletRequest request){

        //从session中获取会员信息
        User user = (User) request.getSession().getAttribute(UserService.USER_SESSION_KEY);

        log.info("------password:"+ user.getPassword());

        try{


            if(StringUtils.isBlank(password)) throw new Exception("原密码不能为空");

            if(StringUtils.isBlank(newPassword)) throw new Exception("新密码不能为空");

            //检查原密码是否正确
            password = MD5Util.parseStrToMd5L32(password);

            log.info("------password:"+password+"    newPasswrod:"+newPassword);


            if(password.equals(user.getPassword())){

                //保存新密码到数据库
                user.setPassword(MD5Util.parseStrToMd5L32(newPassword));

                userBaseDao.update(user);

                return new JsonReturn(1,"修改密码成功");

            }else{

                throw new Exception("原登陆密码不正确");
            }

        }catch (Exception e){

            e.printStackTrace();

            log.error(String.valueOf(e));

            return new JsonReturn(0,"修改密码失败！错误信息:"+e.getMessage());

        }


    }

}
